-- Copyright (c) 2025 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local class = require 'mc.class'
local singleton = require 'mc.singleton'
local consts = require 'constants'
local log = require 'mc.logging'

local module = class{}

local tcp_service_fmt = 'tcp://ipv4:%s:%s:1'

local listen_prop = {
    ['Enabled'] = true,
    ['SyncRole'] = true,
    ['Address'] = true,
    ['Port'] = true
}

function module:ctor()
    self.tcp_enabled = false
    self.sync_role = nil
    self.identifier = nil
    self.address = nil
    self.port = nil
    self.service_address = nil
end

function module:register(mdb_object, tcp_signal, address_sig, role)
    mdb_object.property_changed:on(function(name, value, _)
        if not listen_prop[name] then
            return
        end

        if name == 'Enabled' then
            self.tcp_enabled = value
            tcp_signal:emit(name, value)
        elseif name == 'SyncRole' then
            self.sync_role = value
            tcp_signal:emit(name)
        elseif name == 'Address' then
            self.address = value
            self.service_address = string.format(tcp_service_fmt, value, self.port)
            address_sig:emit()
        elseif name == 'Port' then
            self.port = value
            self.service_address = string.format(tcp_service_fmt, self.address, value)
            address_sig:emit()
        end
    end)
    self.sync_role = role
    self.tcp_enabled = mdb_object.Enabled
    self.identifier = mdb_object.Identifier
    self.address = mdb_object.Address
    self.port = mdb_object.Port
    self.service_address = string.format(tcp_service_fmt, self.address, self.port)
    -- 补充信号，避免时序问题
    tcp_signal:emit('Enabled')
    log:notice('inti service address [%s]', self.service_address)
end

function module:get_sync_role()
    if not self.tcp_enabled then
        return consts.DATASYNC_ROLE_DISABLED
    end
    return self.sync_role
end

return singleton(module)